<template>
  <el-card class="quick-meeting-card">
    <div class="card-header">快速会议</div>

    <!-- 操作按钮组 -->
    <div class="button-group">
      <el-button
        :loading="isCreatingMeeting"
        type="primary"
        icon="el-icon-video-camera"
        class="primary-btn"
        @click="startInstantMeeting"
      >
        {{ isCreatingMeeting ? '创建中...' : '立即会议' }}
      </el-button>


      <el-popover
        placement="bottom"
        trigger="click">

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-s-promotion"
              size="mini"
              @click="invited"
              :disabled="single"
            >发起预约
            </el-button>
          </el-col>

          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              @click="deleteMeeting"
              :disabled="single"
            >删除预约
            </el-button>
          </el-col>
        </el-row>

        <el-table v-loading="loading" :data="gridData" @selection-change="handleSelectionChange" style="margin-top: 10px">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column  align="center" property="nickName" label="用户"/>
          <el-table-column  align="center" property="sex" label="性别">
            <template slot-scope="scope">
              <span>{{scope.row.sex === 0 ? '男' : scope.row.sex === 1 ? '女' : '未知'}}</span>
            </template>
          </el-table-column>
          <el-table-column  align="center" property="phonenumber" width="160" label="电话"/>
          <el-table-column  align="center" property="deptName" label="部门">
            <template slot-scope="scope">
              <span>{{scope.row.deptName ? scope.row.deptName : '无'}}</span>
            </template>
          </el-table-column>
          <el-table-column  align="center" property="postName" label="职位">
            <template slot-scope="scope">
              <span>{{scope.row.postName ? scope.row.postName : '无'}}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-s-promotion"
                @click="send(scope.row)"
              >发起预约
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                v-show="scope.row.userId !== null"
                @click="deleteMeeting(scope.row)"
              >删除预约
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-button
          style="width: 350px"
          slot="reference"
          icon="el-icon-calendar"
          class="default-btn"
          @click="openReservationDialog"
        >
          预约会议
        </el-button>

        <div style="margin-top: 20px">
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </div>
      </el-popover>
    </div>

    <!-- 会议号区域 -->
    <div class="meeting-id-container">
      <label class="id-label">我的会议号</label>
      <div class="id-content">
        <el-input v-model="displayMeetingId" readonly class="id-input"></el-input>
        <el-button
          type="text"
          class="copy-btn"
          @click="copyMeetingId"
          :disabled="!meetingId"
        >
          {{ copyStatus ? '已复制' : '复制' }}
        </el-button>
      </div>
    </div>

    <!-- 加入会议区域 -->
    <el-input
      v-model="joinId"
      placeholder="输入会议号加入会议"
      class="join-input"
      clearable
      @keyup.enter.native="handleJoinMeeting"
    ></el-input>
    <el-button
      type="primary"
      class="join-btn"
      @click="handleJoinMeeting"
      :disabled="!joinId.trim()"
    >
      加入会议
    </el-button>

    <el-dialog width="30%" title="会议邀请" :visible.sync="dialogVisible">
      <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
        <el-form-item label="会议名称" prop="meetingName">
          <el-input v-model="formData.meetingName" placeholder="请输入会议名称" clearable :style="{width: '100%'}">
          </el-input>
        </el-form-item>
        <el-form-item label="日期选择" prop="meetingTime">
          <el-date-picker type="datetime" v-model="formData.meetingTime" format="yyyy-MM-dd HH:mm:ss"
                          value-format="yyyy-MM-dd HH:mm:ss" :style="{width: '100%'}" placeholder="请选择日期选择"
                          clearable>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="formData.password" placeholder="请输入密码" clearable show-password
                    :style="{width: '100%'}"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="close()">取消</el-button>
        <el-button type="primary" @click="handleConfirm()">确定</el-button>
      </div>
    </el-dialog>


  </el-card>
</template>

<script>
import { addTermsInvitationInfo, conferenceMeeting, deleteMenuById, getLoginUserInvitationInfo } from '@/api/meeting'

export default {
  name: 'QuickMeetingCard',
  data () {
    return {
      formData: {
        userId: [],
        meetingName: null,
        meetingDate: null,
        meetingTime: null,
        password: null,
      },
      meetingId: '',
      joinId: '',
      displayMeetingId: '加载中...',
      isCreatingMeeting: false,
      copyStatus: false,
      loadingTimer: null,
      fetchInterval: null,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      gridData: [],
      ids:[],
      invitedIds:[],
      multiple: true,
      single: true,
      dialogVisible: false,
      rules: {
        meetingName: [{
          required: true,
          message: '请输入会议名称',
          trigger: 'blur'
        }],
        meetingTime: [{
          required: true,
          message: '请选择开始时间',
          trigger: 'change'
        }],
        password: [{
          required: true,
          message: '请输入会议密码',
          trigger: 'blur'
        }],
      },
      // 遮罩层加载
      loading: false,
    }
  },
  created () {
    this.fetchMeetingId()
  },
  beforeDestroy () {
    if (this.loadingTimer) clearTimeout(this.loadingTimer)
    if (this.fetchInterval) clearInterval(this.fetchInterval)
  },
  methods: {
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.single = selection.length === 0
      this.ids = []
      this.email = []
      selection.forEach(item => {
        this.ids.push(item.askedId)
        this.email.push(item.email)
        this.invitedIds.push(item.id)
      })
    },    /**
     * 获取会议号（模拟异步）
     */
    fetchMeetingId () {
      this.displayMeetingId = '加载中...'
      this.loadingTimer = setTimeout(() => {
        this.meetingId = this.generateMeetingId()
        this.displayMeetingId = this.meetingId
      }, 800)
    },

    getList () {
      conferenceMeeting(this.queryParams).then(res => {
        this.gridData = res.rows
        this.total = res.total
      })
    },
    /**
     * 生成随机会议号（格式为 123 456 789）
     */
    generateMeetingId () {
      const num = Math.floor(100000000 + Math.random() * 900000000)
      return num.toString().replace(/(\d{3})(\d{3})(\d{3})/, '$1 $2 $3')
    },

    /**
     * 复制会议号到剪贴板
     */
    async copyMeetingId () {
      if (!this.meetingId) return

      try {
        await navigator.clipboard.writeText(this.meetingId.replace(/\s/g, ''))
        this.copyStatus = true
        this.$message.success('会议号已复制到剪贴板', 1500)
        setTimeout(() => {
          this.copyStatus = false
        }, 2000)
      } catch (e) {
        this.$message.error('复制失败，请手动复制')
      }
    },

    /**
     * 加入会议
     */
    handleJoinMeeting () {
      const id = this.joinId.trim()

      if (!id) {
        this.$message.warning('请输入有效的会议号')
        return
      }

      const cleanId = id.replace(/\s/g, '')
      if (!/^\d{9}$/.test(cleanId)) {
        this.$message.warning('会议号格式不正确')
        return
      }

      this.$message.success(`正在加入会议 ${cleanId}...`)
      setTimeout(() => {
        this.joinId = ''
      }, 1500)
    },

    /**
     * 开始立即会议
     */
    startInstantMeeting () {
      this.isCreatingMeeting = true
      this.$message.info('正在创建会议...')

      // 模拟 API 调用
      setTimeout(() => {
        this.isCreatingMeeting = false
        this.meetingId = this.generateMeetingId()
        this.displayMeetingId = this.meetingId
        this.$message.success('会议已创建，正在进入会议室...')
      }, 1500)
    },

    /**
     * 打开预约会议对话框
     */
    openReservationDialog () {
      this.getList()
    },
    close() {
      // 打卡对话框
      this.dialogVisible = false
      // 取消的提醒
      this.$message('您已取消邀请');
      // 重置表单
      this.formData = {
        meetingName: '',
        meetingDate: null,
        meetingTime: '',
        password: '',
      }
      // 重置表单校验
      this.$refs['elForm'].resetFields()
    },
    // 页面加载时加载数据
    loadData() {
      this.loading = true
      getLoginUserInvitationInfo(this.queryParams).then(res => {
        this.postList = res.rows
        this.total = res.total
      })
      this.loading = false
    },
    // 校验表单并发送邀请单选
    handleConfirm() {
      this.$refs['elForm'].validate(valid => {
          if (valid) {
            const formData = this.formData;
            formData.email = this.email;
            addTermsInvitationInfo(formData).then(res => {
              this.$message({
                type: 'success',
                message: `成功邀请${res.data}人!`
              });
              this.$refs['elForm'].resetFields()
              // 清空表单
              this.formData = {
                userId: [],
                meetingName: '',
                meetingDate: null,
                meetingTime: '',
                password: '',
              }
              // 关闭对话框
              this.dialogVisible = false
              // 在查询一遍数据
              this.loadData()
            })
          }
        }
      )
    },
    // 发送邀请单选
    send(row) {
      this.dialogVisible = true
      this.email = []
      this.email.push(row.email)
      this.formData.userId = [row.askedId]
    },
    // 发送邀请d多选
    invited() {
      this.dialogVisible = true
      this.formData.userId = this.ids
    },
    // 删除会议
    deleteMeeting(row) {
      this.$confirm('此操作将永久取消该邀请, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let id
        if (row.id) {
          id = row.id
        } else {
          id = this.invitedIds
        }
        deleteMenuById(id).then(res => {
          // 从新调用页面加载
          this.loadData()
          // 提示信息
          this.$message({
            type: 'success',
            message: `已取消${res.data}个会议!`
          });
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
  }
}
</script>

<style lang="less" scoped>
.quick-meeting-card {
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  }

  .card-header {
    font-size: 19px;
    font-weight: 800;
    color: #333;
    padding-bottom: 12px;
    margin-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;
  }

  .button-group {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;

    .primary-btn,
    .default-btn {
      flex: 1;
      height: 44px;
      font-size: 14px;
      border-radius: 6px;
      transition: all 0.2s ease;
    }

    .primary-btn {
      background-color: #409eff;
      border: none;
      color: #fff;

      &:hover {
        background-color: #3088e6;
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
      }

      &:active {
        transform: translateY(0);
      }
    }

    .default-btn {
      background-color: #fff;
      color: #333;
      border: 1px solid #dcdfe6;

      &:hover {
        background-color: #f5f7fa;
        border-color: #c0c4cc;
        transform: translateY(-1px);
      }

      &:active {
        transform: translateY(0);
      }
    }
  }

  .meeting-id-container {
    margin-bottom: 16px;

    .id-label {
      display: block;
      font-size: 14px;
      color: #606266;
      margin-bottom: 6px;
    }

    .id-content {
      display: flex;
      align-items: center;
      gap: 10px;

      .id-input {
        flex: 1;
        height: 40px;
        background-color: #f5f7fa;
        border: 1px solid #e4e7ed;
        border-radius: 4px;
        cursor: not-allowed;
        transition: all 0.2s ease;

        &:hover {
          border-color: #dcdfe6;
        }
      }

      .copy-btn {
        color: #409eff;
        font-size: 14px;
        padding: 0;
        transition: all 0.2s ease;

        &:hover {
          color: #3088e6;
          transform: translateY(-1px);
        }

        &:active {
          transform: translateY(0);
        }

        &[disabled] {
          color: #c0c4cc;
          cursor: not-allowed;
        }

        &.success {
          color: #67c23a;
        }
      }
    }
  }

  .join-input {
    height: 40px;
    margin-bottom: 14px;
    border-radius: 4px;
    transition: all 0.2s ease;

    &:focus {
      border-color: #409eff;
      box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
    }
  }

  .join-btn {
    width: 100%;
    height: 44px;
    font-size: 14px;
    border-radius: 6px;
    background-color: #409eff;
    border: none;
    color: #fff;
    transition: all 0.2s ease;

    &:hover {
      background-color: #3088e6;
      transform: translateY(-1px);
      box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
    }

    &:active {
      transform: translateY(0);
    }
  }
}
</style>
